<template>
  <div>
    <div><el-button type="plain" @click="$router.back()" size="mini">返回</el-button></div>
    <div id="areaWrapper">
      <div v-loading="loading"
           element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(255, 255, 255, 0.8)"
           id="scrollWrapperWf" class="left"
           :style="{width:'30%'}">
        <!--  overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width: 50%-->
        <div style="display: flex;justify-content: space-between;align-items:center;padding: 5px 10px">
          <div style="font-size: .9rem;">
<!--            <img style="width: .9rem;height: .9rem;" src="./assets/icon.png" alt="">-->
            <span>报告名称： {{report.reportName}}</span>
          </div>
          <div style="display: flex;justify-content: space-between;">
            <div>
              <el-tooltip content="成功" placement="top" effect="light">
                <el-tag style="font-size: .9rem;background-color:yellowgreen;color: #fff">{{report.successCount}}</el-tag>
              </el-tooltip>
            </div>
            <div>
              <el-tooltip content="停止" placement="top" effect="light">
                <el-tag style="font-size: .9rem;background-color:rgb(204, 204, 0);color: #fff">{{report.stoppedCount}}</el-tag>
              </el-tooltip>
            </div>
            <div>
              <el-tooltip content="失败" placement="top" effect="light">
                <el-tag style="font-size: .9rem;background-color:red;color: #fff">{{report.errorCount}}</el-tag>
              </el-tooltip>
            </div>
            <div>
              <el-tooltip content="阻塞" placement="top" effect="light">
                <el-tag style="font-size: .9rem;background-color:gray;color: #fff ">{{report.pendingCount}}</el-tag>
              </el-tooltip>
            </div>

            <!--  <div>
                <el-tag style="font-size: .9rem;background-color:brown;color: #fff">{{report.unknownCount}}</el-tag>
              </div>-->
          </div>
        </div>

        <div>
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="leftTree"
            node-key="id"
            :current-node-key="currentNodeKey"
            :default-expanded-keys="expandedKeys"
            :expand-on-click-node="false"
            :props="defaultProps"
            :highlight-current="true"
            :filter-node-method="filterNode"
            default-expand-all
            @node-click="leftClick"
          >
            <!-- check-strictly -->
            <div slot-scope="{ node, data }" class="custom-tree-node">

            <span class="em-tree-text" :title="data.scenarioName" style="font-size: .9rem;">

              <span>
               <span v-if="data.status=='SUCCESS'"> <i style="color: #67c23a" class="el-icon-success"></i></span>
                <!--null => pending-->
               <span v-else-if="data.status==null || data.status=='PENDING'"> <i style="color: gray" class="el-icon-warning"></i></span>
               <span v-else-if="data.status=='STOPPED'"> <i style="color:rgb(204, 204, 0);" class="el-icon-close-notification"></i></span>
               <span v-else><i style="color: red" class="el-icon-error"></i></span>
               <span>{{data.scenarioName ||data.name}}</span>
              </span>
            </span>

              <span class="operation" style="font-size: .9rem;" v-if="data.hasOwnProperty('scenarioName')">
                <el-tag style="font-size: .9rem;background-color:#67c23a;color: #fff">{{data.stepTotal}}</el-tag>
              </span>

            </div>
          </el-tree>
        </div>
      </div>

      <div class="right"
           v-loading="loading2"
           element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(255, 255, 255, 0.8)">
          <div v-if="rowData.scenarioId && !stepInfo.id">

            <el-descriptions style="margin-top: 20px;" class="margin-top" :column="1" size="medium" border>
              <el-descriptions-item>
                <template slot="label">
                  模块路径
                </template>
                {{rowData.modulePath}}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  场景名称
                </template>
                {{rowData.scenarioName}}
              </el-descriptions-item>


              <el-descriptions-item>
                <template slot="label">
                  创建人
                </template>
                {{rowData.creator}}

              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  等级
                </template>
                {{ rowData.level }}

              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label">
                  创建时间
                </template>
                {{rowData.createTime}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  结束时间
                </template>
                {{rowData.endTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  触发方式
                </template>
                {{rowData.triggerMode}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  状态
                </template>
                <div style="white-space: pre-line;">
                  {{rowData.status}}
                </div>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  步骤总数
                </template>
                <div style="white-space: pre-line;">
                  {{rowData.stepTotal}}
                </div>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  场景报告名称
                </template>
                <div style="white-space: pre-line;">
                  {{rowData.scenarioNameReportName}}
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="stepInfo.id">
            <h2>{{stepInfo.label}} </h2>
            <hr>
            <!---->
            <h3 style="color: rgba(255,0,0,.5)" v-if="stepInfo.status=='failed' || stepInfo.status== 'broken'">错误总结</h3>
            <!--     "-->
            <div>
              <el-collapse v-if="stepInfo.status=='failed' || stepInfo.status== 'broken'">
                <el-collapse-item>
                  <div slot="title">
                    <el-button type="danger">{{stepInfo.errorSummary}}</el-button>
                  </div>
                  <div style="background-color:rgba(255,0,0,.1);padding: 1rem;min-height: 10rem;border-radius: 5px;white-space: pre">
                    {{stepInfo.errorDetail}}
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>

            <h3>断言</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="position: absolute;right:0;top:0"><el-button type="primary" v-clipboard:copy="stepInfo.assertions" v-clipboard:success="clipboardSuccess"  size="mini" :disabled="!stepInfo.assertions">复制</el-button></div>

              <div style="white-space: pre-wrap;word-break: break-all">{{JSON.parse(stepInfo.assertions)}}</div>
            </div>
            <h3>请求时间</h3>

            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="white-space: pre-wrap;word-break: break-all">创建时间： {{stepInfo.createTime}}</div>
              <div style="white-space: pre-wrap;word-break: break-all">结束时间： {{stepInfo.endTime}}</div>
            </div>
            <h3>
              <span>请求头</span>
              <el-button style="margin-left: 10px" size="mini" v-if="headFlag" @click="headFlag=false">隐藏</el-button>
              <el-button style="margin-left: 10px" size="mini" v-else @click="headFlag=true">展示</el-button>
            </h3>

            <div class="paramsArea" v-if="headFlag" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.requestHeader}}</div>
            </div>

            <h3>请求方式</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' :'rgba(0,255,55,.1)'}">
              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.method}}</div>
            </div>

            <h3>请求URL地址</h3>

            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="position: absolute;right:0;top:0"><el-button type="primary" v-clipboard:copy="stepInfo.url" v-clipboard:success="clipboardSuccess"  size="mini" :disabled="!stepInfo.url">复制</el-button></div>
              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.url}}</div>
            </div>
            <h3>请求体参数</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' :'rgba(0,255,55,.1)'}">
              <div style="position: absolute;right:0;top:0"><el-button type="primary" v-clipboard:copy="stepInfo.requestBody" v-clipboard:success="clipboardSuccess"  size="mini" :disabled="!stepInfo.requestBody">复制</el-button></div>
              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.requestBody}}</div>
            </div>
            <h3>响应结果</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="position: absolute;right:0;top:0"><el-button type="primary" v-clipboard:copy="stepInfo.responseResult" v-clipboard:success="clipboardSuccess"  size="mini" :disabled="!stepInfo.responseResult">复制</el-button></div>
              <div style="color:#4A9FF9;font-style: italic;font-weight: bold;">
                <span> 响应字节数(B)：<el-tag>{{stepInfo.responseSize}}</el-tag></span>
                <span> 响应时间(毫秒)：<el-tag>{{stepInfo.responseTime}}</el-tag></span>
               </div>
              <div style="white-space: pre-wrap;word-break: break-all">
<!--                <div v-for="(value,key) in stepInfoResult">-->
<!--                  <div v-if="key !=='body'">-->
<!--                    <span>{{key}}</span> : <span>{{value}}</span>-->
<!--                  </div>-->
<!--                  <div v-if="key=='body'">-->
<!--                    <span>{{key}}</span> : <span>{{value}}</span>-->
<!--                  </div>-->
<!--                </div>-->
                <span>{{stepInfo.responseResult}}</span>
              </div>

            </div>



            <h3>提取变量</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">
              <div style="position: absolute;right:0;top:0"><el-button v-clipboard:copy="stepInfo.vars" v-clipboard:success="clipboardSuccess" type="primary" size="mini" :disabled="!stepInfo.vars">复制</el-button></div>

              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.vars}}</div>
            </div>

            <h3>最终结果</h3>
            <div class="paramsArea" :style="{backgroundColor:stepInfo.status == 'ERROR'? 'rgba(255,0,0,.1)' : 'rgba(0,255,55,.1)'}">

              <div style="white-space: pre-wrap;word-break: break-all">{{stepInfo.status == null? 'PENDING': stepInfo.status}}</div>
            </div>
          </div>
      </div>

    </div>
  </div>

</template>

<script>

  import domain from '../../../domain.js'
  import qs from "qs"

  const base = domain.target
  export default {
    name: 'InstanceManagement',
    components: {},
    data() {
      return {
        headFlag:false,
        loading:false,
        loading2:false,
        report: {},
        stepInfo: {},
        stepInfoResult:{},
        stepInfoParams: [],
        mechanismType: '0',
        mechanismId: '', // 机构id
        selectedNode: {}, // 选中的结构数据
        selectedObj: {}, // 选中的结构数据
        selectedPersonneData: [],
        selectedPersonneObj: {},
        personneObj: {},
        nodeType: '',
        showExcelVisible: false,
        statusData: [],
        roleData: [],
        persondialogTitle: "新增",
        rowData: {},

        addOrEdit: "",
        addEditCasesModelVisible: false,
        filterText: "",
        leftTree: [],
        currentNodeKey: "",
        expandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'scenarioName'
        },
        firstLoad: true,
        leftResourceNode: {},
        leftResourceNodes: {},//点的当前节点
        parentResourceId: "",
        leftResourceID: "",
        selectedRows: [],
      }
    },
    computed: {},
    created() {
      let reportId = this.$route.query.reportId
      this.report.reportName = this.$route.query.reportName
      // this.report.brokenCount = this.$route.query.brokenCount
      this.report.errorCount = this.$route.query.errorCount
      this.report.successCount = this.$route.query.successCount
      this.report.pendingCount = this.$route.query.pendingCount
      this.report.stoppedCount = this.$route.query.stoppedCount
      // this.report.unknownCount = this.$route.query.unknownCount

      this.findTree(reportId)


    },
    mounted() {

    },
    methods: {


      leftClick(data, node) {
        console.log(data)
        if (!data) return
        if (this.loading2) return
        if (data.hasOwnProperty("scenarioId")) {
          this.stepInfo = {}
          this.stepInfoResult = {}
          console.log(data)
          this.rowData = data
          let scenarioId = data.scenarioId
          this.$get(`${base}/ms/steps/info?scenariosId=${scenarioId}`, {}).then(res => {
            if (res && res.data.code == 20000) {
              let tree = res.data.obj || []
              this.leftTree.forEach((item)=>{
                if (item.scenarioId ==data.scenarioId){
                  this.$set(item,"children",tree)
                }

              })
            }
          })
        }

        else if (data.hasOwnProperty("status") && !data.hasOwnProperty("reportId")){
          this.loading2= true
          console.log(data)
          this.stepInfo = {}
          let stepId = data.stepId
          let params = {
            stepId
          }

          this.$get(`${base}/ms/step/info`, {params}).then(res => {
            if (res && res.data.code == 20000) {
              this.stepInfo = res.data.obj
              this.rowData = {}
              this.stepInfoResult = JSON.parse(this.stepInfo.responseResult)
              console.log( "this.stepInfoResult",this.stepInfoResult)
              this.loading2= false
            }
          })
        }else{

        }

      },
      clipboardSuccess(){
        this.$message.success("复制成功")
      },
      // 初始化树
      findTree(reportId) {
        // this.tradeData = []
        this.leftTree = []
        let params = {
          reportId
        }
        this.loading = true
        this.$get(`${base}/ms/Scenarios`, {params}).then(res => {
          if (res && res.data.code == 20000) {
            // debugger
            console.log("treeData", res.data)
            this.$nextTick(() => {

              this.leftTree = res.data.obj || []
              // this.leftTree.forEach((item)=>{
              //   this.$set(item,"children",[])
              // })
              this.loading = false
              console.log("结果",this.leftTree)
              // this.parentResourceId = this.leftTree[0].parentResourceId || ""
              // this.leftResourceNode = this.leftTree
            })
          }
        })

      },

      filterNode(value, data, node) {
        console.log("筛选节点", value)
        if (!value) {
          // this.collapseAll()
          return true
        }
        // const level = node.level
        const _array = []// 这里使用数组存储 只是为了存储值。
        this.getReturnNode(node, _array, value)
        let result = false
        _array.forEach((item) => {
          result = result || item
        })
        console.log("result", result)
        return result
      },

      getReturnNode(node, _array, value) {
        /*忽略大小写*/
        const isPass = node.data && node.label && node.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
        isPass ? _array.push(isPass) : ''
        if (!isPass && node.level != 1 && node.parent) {
          this.getReturnNode(node.parent, _array, value)
        }
      },
      /**========================== 工具函数  =====================*/
      /*   removeNodeInTree(treeList, id) { // 通过id从数组（树结构）中移除元素
           console.log("removeNodeInTree")
           if (!treeList || !treeList.length) {
             return
           }
           for (let i = 0; i < treeList.length; i++) {
             if (treeList[i].id == id) {
               treeList.splice(i, 1);
               break;
             }
             this.removeNodeInTree(treeList[i].children, id)
           }
         },
         deepCopy (obj) {
           if (typeof obj !== 'object') return;
           var newObj = obj instanceof Array ? [] : {};
           for (var key in obj) {
             if (obj.hasOwnProperty(key)) {
               // console.log(`${key}:${obj[key]}`)
               if (obj[key]==null){
                 obj[key] = ""
               }
               newObj[key] = typeof obj[key] === 'object' ? this.deepCopy(obj[key]) : obj[key];// obj[d]= { name:'wf',age:25}
             }
           }
           return newObj;
         },
         // 这种仅用于查找叶子节点
         getCurrentParts(resourceId, items) {
           var result;
           for (let item of items) {
             if (item.resourceId == resourceId && (!item.children || item.children.length ==0 )) { // 条件变更
               result = item;
               // nodePathArray.push(item.key)
               return result
             } else if (item.children && !result) { // 加一个非空判断 不然还会继续往下找

               result = this.getCurrentParts(resourceId, item.children);
               /!*  if (result){
                      return result
                      // nodePathArray.push(item.key)
                 }*!/
             } else {
               console.log(item)
               console.log("未匹配 且没有孩子 或 已经找到值了")
             }
           }
           return result;
         },
         //// 这种可以查找非叶子节点
         getCurrentParts2(resourceId, items) {
           var result;
           for (let item of items) {
             if (item.resourceId == resourceId) {
               result = item;
               // nodePathArray.push(item.key)
               return result
             } else if (item.children && !result) { // 加一个非空判断 不然还会继续往下找

               result = this.getCurrentParts2(resourceId, item.children);
               /!*  if (result){
                      return result
                      // nodePathArray.push(item.key)
                 }*!/
             } else {
               console.log(item)
               console.log("未匹配 且没有孩子 或 已经找到值了")
             }
           }
           return result;
         },*/
    },

    /* 查询 存在问题 后面再看*/
    watch: {
      filterText(val) {
        console.log("val", val)
        if (val) {
          this.$refs.tree.filter(val)
        } else {
          // this.findTree()
        }
      },
      'leftResourceID': {
        //立即监听
        //监听到carouselList状态发生变化了
        handler(val) {
          //监听到数据后的下一步操作
          // console.log("leftResourceID",val)
        },
        immediate: false,
      },
      // 初次加载全部用例
      leftTree: {
        deep: true,
        immediate: true,
        handler: function (newValue, oldValue) {
          console.log("leftTree值:", newValue, oldValue);
          // if(this.firstLoad && newValue.length>0){
          //   this.leftClick(newValue[0])
          //   this.firstLoad=false
          // }
        },
      }
    },
  }
</script>

<style scoped lang="scss">
  #areaWrapper {
    width: 100%;
    height: 97vh;
    margin: 0px auto;
    overflow: auto;
    /*padding-top: 20px;*/
    /*border:1px solid;*/
    background-color: #fff;
    display: flex;
    justify-content: space-between;

    .left {
      height: 100%;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      box-shadow: 3px 3px 3px 1px rgba(224, 200, 209, 0.2);
      overflow: auto;
    }

    .right {
      margin-left: 15px;
      height: 100%;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      box-shadow: 3px 3px 3px 1px rgba(224, 200, 209, 0.2);
      overflow: auto;
      flex: 1;
      padding: 0 25px 25px 25px;
    }
  }

  .tree-search {
    width: 80%;
  }

  .left-tree-inner-wrapper {
    width: 100%;
    overflow: auto;
  }

  ::v-deep .el-tree-node > .el-tree-node__children {
    overflow: inherit;
  }

  ::v-deep .el-tree-node__content {
    font-size: 14px;
  }

  .custom-tree-node {
    display: flex;
    flex: 1;
    width: 100%;
    align-items: center;
    justify-content: space-between;
    padding-right: 10px;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    .em-tree-text {
      display: inline-block; //block一样
      overflow: hidden;
      white-space: nowrap;

      text-overflow: ellipsis;
    }

    .operation {
      position: absolute;
      right: 0;
    }
  }

  ::v-deep .el-tree-node__content {
    border-bottom: 1px solid #e8e8e8;
  }

  .paramsArea {
    min-height: 50px;
    padding: 10px;
    background-color:rgba(0,255,55,.1);
    border-radius: 5px;
    position: relative;
    box-shadow: 2px 2px 4px 4px rgba(224, 200, 209, .5);
    div {
      margin-top: 10px;

    }
  }

  /* 修改 hr 标签的颜色为蓝色，设置线宽和线型 */
  hr {
    border: 1px solid #e8e8e8;
  }

  ::v-deep .el-collapse-item__arrow{
    font-size: 30px;
    color:red
  }

  ::v-deep .el-descriptions-item__label.is-bordered-label{
    width: 200px;
  }
</style>

<!--自定义滚动条样式-->
<style>
  #scrollWrapperWf::-webkit-scrollbar, #leftMenuWrapper::-webkit-scrollbar { /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 8px;
    display: block;
    scrollbar-arrow-color: #bfa;
  }

  #scrollWrapperWf::-webkit-scrollbar-thumb, #leftMenuWrapper::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: darkgray;
    /*background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);*/
  }

  #scrollWrapperWf::-webkit-scrollbar-track, #leftMenuWrapper::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    background: #e8e8e8;
  }

  /*::-webkit-scrollbar-button – 滚动条两端的上/下（或左/右）按钮*/
  /*  #scrollWrapperWf::-webkit-scrollbar-button{
       width: 4px;
       height: 4px;
       !*background-color: #b0b0b0;*!
       border-radius:4px ;
       background-size: 100%;
       background-position: center;
     }*/
  /*::-webkit-scrollbar– 滚动条轨道未被滑块覆盖的部分*/
  #scrollWrapperWf::-webkit-scrollbar-track-piece, #leftMenuWrapper::-webkit-scrollbar-track-piece {
    /*background-color: #bfa;*/
  }

  /*::-webkit-scrollbar-corner – 垂直滚动条和水平滚动条交汇的部分*/
  #scrollWrapperWf::-webkit-scrollbar-corner {
    width: 4px;
    height: 4px;
    /*background-color: #34bfa3;*/
    border-radius: 4px;
    background-size: 100%;
    background-position: center;

  }

  /*放上样式*/
  #scrollWrapperWf::-webkit-scrollbar-thumb:hover {
    background-color: darkgray;
  }

  /*点击样式*/
  #scrollWrapperWf::-webkit-scrollbar-thumb:active {
    background-color: darkgray;
  }

</style>
